home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 947 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.6 KB

  1. Path: news.iag.net!news
  2. From: jatmon@iag.net (John R Buchan)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Help on Dynamically Allocating an Array?
  5. Date: 10 Jan 1996 12:55:28 GMT
  6. Organization: Internet Access Group, Orlando, Florida
  7. Message-ID: <4d0d00$7aq@news.iag.net>
  8. References: <4cq273$aeq@mercury.IntNet.net> <4cvm5n$9au@gryphon.phoenix.net>
  9. NNTP-Posting-Host: pm1-orl23.iag.net
  10. X-Newsreader: WinVN 0.99.7
  11.  
  12. In article <4cvm5n$9au@gryphon.phoenix.net>, brucew@phoenix.net says...
  13. >
  14. >jtomich@IntNet.net (Jeff Tomich) wrote:
  15. >
  16. >>I'm confused on who to dynamically allocate an array of any type. Any 
  17. >>help would be much appreciated.
  18. >
  19. >char *p = malloc( numitems );
  20. >
  21. >
  22. >Bruce D. Wedding                        Have Compiler, Will Travel!
  23. >              Perspicacious Programming Performed Promptly
  24. >Katy, Texas, USA, Planet Earth, Milkyway Galaxy, Known Universe
  25. >
  26.  
  27. For any type T:
  28.  
  29.    T *ptr = malloc( numitems * sizeof(T)); 
  30.    if( ptr == NULL)
  31.       {
  32.       /* allocation failed. handle it */
  33.       }
  34.  
  35.    /* use the array */
  36.    free( ptr);  /* free the memory, when no longer needed */
  37.  
  38. Because sizeof(char) == 1 by ansi definition, it is simpler to write the 
  39. malloc for a char array without the "* sizeof(char)", as demonstrated 
  40. by Bruce D. Wedding 
  41.  
  42. You might want to d/l and read through the c.l.c faq (Frequently Asked
  43. Question) list.  If contains a considerable amount of useful information
  44. about pointers and dynamic allocation.  It is available for anonymous ftp
  45. from rtfm.mit.edu /pub/usenet/comp.lang.c.
  46.  
  47. -- 
  48. John R Buchan           -:|:-     Looking for that elusive FAQ?  ftp to:
  49. jatmon@mail.iag.net     -:|:-     rtfm.mit.edu /pub/usenet-by-group/....
  50.  
  51.